use std::{net::TcpListener, process::Command, sync::OnceLock};

use encoding_rs::GBK;
use serde::{Deserialize, Serialize};
use tracing::info;

#[derive(Deserialize, Debug, Serialize)]
pub struct WxUser {
    pub wx_id: String,
    wx_account: String,
    pub nick_name: String,
    avatar_url: String,
    nation: String,
    province: String,
    city: String,
    mobile: String,
    // 性别
    // - 0 未设置
    // - 1 男
    // - 2 女
    gender: u8,
    // 登录设备
    device: String,
    // 缓存目录
    cache_dir: String,
}

#[derive(Clone, Deserialize, Debug, Serialize)]
pub struct BzUser {
    id: i32,
    group_id: i32,
    username: String,
    /// 用户昵称
    nickname: String,
    /// 手机号
    mobile: String,
    /// 头像
    avatar: String,
    score: i32,
    relation_user_ids: String,
    powerdata: String,
    /// 是否已通过审核
    /// - `0` 审核中
    /// - `1` 通过
    /// - `2` 拒绝
    check_status: String,
    pub token: String,
    user_id: i32,
    createtime: u32,
    expiretime: u32,
    expires_in: u32,
}

pub static BZ_USER: OnceLock<BzUser> = OnceLock::new();

#[derive(Deserialize, Debug)]
pub struct BzLogin {
    #[serde(rename = "userinfo")]
    pub user_info: BzUser,
}

pub static USER: OnceLock<WxUser> = OnceLock::new();

fn find_free_port() -> Option<u16> {
    TcpListener::bind("127.0.0.1:0")
        .ok()
        .map(|listener| listener.local_addr().unwrap().port())
}

pub fn get_port() -> (&'static u16, &'static u16) {
    static SEND_PORT: OnceLock<u16> = OnceLock::new();
    static LISTEN_PORT: OnceLock<u16> = OnceLock::new();

    (
        SEND_PORT.get_or_init(|| find_free_port().expect("Failed to find free port for sending")),
        LISTEN_PORT
            .get_or_init(|| find_free_port().expect("Failed to find free port for listening")),
    )
}

pub fn init_wx() {
    let (send, listen) = get_port();

    println!("send: {send}, listen: {listen}");

    let inject_tool_path = "./tool/dfg/inject_tool";

    if !std::fs::metadata(inject_tool_path).is_ok() {
        eprintln!("Error: {} does not exist", inject_tool_path);
        std::process::exit(1);
    }

    let output = Command::new(inject_tool_path)
        .arg("start")
        .arg(send.to_string())
        .arg(format!("--my_port={listen}"))
        .output()
        .expect("Error executing command");

    let (gbk_output, _, _) = GBK.decode(&output.stdout);

    info!("注入结果: {output:?}, gbk: {gbk_output}");
}
